﻿using MyMes.Infrastructure;
using MyMES.Dto;
using MyMES.IServices.QualityAssurance;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.Utilities.Response;
using VOL.Entity.DomainModels.Core;
using VOL.Entity.DomainModels.QualityAssurance;
using Microsoft.EntityFrameworkCore;
using VOL.Core.Extensions;
using VOL.Entity.DomainModels;

namespace MyMES.Services.QualityAssurance
{
    public class WaitTaskService : IWaitTaskService
    {
        private readonly IBaseRepository<WaitTask> _waitTaskRepository;
        private readonly IBaseRepository<Incominginspection> _incomingInspectionRepository;
        private readonly IBaseRepository<MaterialProduct> _materialProductRepository;

        public WaitTaskService(IBaseRepository<WaitTask> waitTaskRepository, IBaseRepository<Incominginspection> incomingInspectionRepository, IBaseRepository<MaterialProduct> materialProductRepository)
        {
            _waitTaskRepository = waitTaskRepository;
            _incomingInspectionRepository = incomingInspectionRepository;
            _materialProductRepository = materialProductRepository;
        }

        /// <summary>
        /// 添加来料检验记录
        /// </summary>
        /// <param name="incominginspection">来料检验实体</param>
        /// <returns>操作结果</returns>
        public async Task<WebResponseContent> AddIncominginspection(Incominginspection incominginspection)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {

                // 保存数据
                await _incomingInspectionRepository.AddAsync(incominginspection);

                return response.OK("添加来料检验记录成功");
            }
            catch (Exception ex)
            {
                return response.Error($"添加来料检验记录失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 获取待检任务列表
        /// </summary>
        /// <param name="dto">查询参数</param>
        /// <returns>分页数据</returns>
        public async Task<PageGridData<WaitTaskDto>> GetWaitTask(GetWaitTaskDto dto)
        {
            try
            {
                // 构建基础查询
                var query = from wt in _waitTaskRepository.GetAll()
                            join mp in _materialProductRepository.GetAll()
                            on wt.MaterialCode equals mp.MaterialCode into mpJoin
                            from mp in mpJoin.DefaultIfEmpty()
                            select new WaitTaskDto
                            {
                                Id = wt.Id,
                                WaitTaskCode = wt.WaitTaskCode,
                                WaitTaskType = wt.WaitTaskType,
                                WaitTaskTypeDetail = wt.WaitTaskTypeDetail,
                                MaterialCode = wt.MaterialCode,
                                MaterialName = mp != null ? mp.MaterialName : wt.MaterialCode,
                                Num = wt.Num,
                                Flats =  mp.Flats 
                            };

                // 应用筛选条件
                query = query.WhereIF(!string.IsNullOrEmpty(dto.WaitTaskCode),
                    x => x.WaitTaskCode.Contains(dto.WaitTaskCode));

                query = query.WhereIF(!string.IsNullOrEmpty(dto.WaitTaskType),
                    x => x.WaitTaskType.Contains(dto.WaitTaskType));

                query = query.WhereIF(!string.IsNullOrEmpty(dto.MaterialName),
                    x => x.MaterialName.Contains(dto.MaterialName));

                // 计算总记录数
                int totalCount = await query.CountAsync();

                // 应用分页并获取数据
                var pagedResults = await query
                    .OrderByDescending(x => x.WaitTaskCode)
                    .Skip((dto.PageIndex - 1) * dto.PageSize)
                    .Take(dto.PageSize)
                    .ToListAsync();

                // 返回分页数据
                return new PageGridData<WaitTaskDto>
                {
                    rows = pagedResults,
                    total = totalCount
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"获取待检任务列表失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 根据ID获取待检任务详情
        /// </summary>
        /// <param name="id">待检任务ID</param>
        /// <returns>待检任务详情</returns>
        public async Task<WebResponseContent> GetWaitTaskById(int id)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                if (id <= 0)
                {
                    return response.Error("无效的待检任务ID");
                }

                // 根据ID查询待检任务
                var query = from wt in _waitTaskRepository.GetAll()
                            join mp in _materialProductRepository.GetAll()
                            on wt.MaterialCode equals mp.MaterialCode into mpJoin
                            from mp in mpJoin.DefaultIfEmpty()
                            where wt.Id == id
                            select new WaitTaskDto
                            {
                                Id = wt.Id,
                                WaitTaskCode = wt.WaitTaskCode,
                                WaitTaskType = wt.WaitTaskType,
                                WaitTaskTypeDetail = wt.WaitTaskTypeDetail,
                                MaterialCode = wt.MaterialCode,
                                MaterialName =  mp.MaterialName ,
                                Num = wt.Num,
                                Flats = mp.Flats,
                            };

                var waitTask = await query.FirstOrDefaultAsync();

                if (waitTask == null)
                {
                    return response.Error("未找到指定的待检任务");
                }

                return response.OK("获取待检任务详情成功", waitTask);
            }
            catch (Exception ex)
            {
                return response.Error($"获取待检任务详情失败：{ex.Message}");
            }
        }
    }
}
